package com.kehutong.admin.entity;

import org.coraframework.cache.Cache;
import org.coraframework.json.annotation.JSONField;
import org.coraframework.orm.Entity;
import org.coraframework.orm.annotation.Column;
import org.coraframework.orm.annotation.Table;
import org.coraframework.orm.annotation.UnSave;

/**
 * 系统缓存
 * 
 * @author liuzhen (liuxing521a@163.com)
 * @createTime 2020年6月19日下午4:51:37
 */
@Table("sys_cache")
public class MCache extends Entity {
	/** 先进先出*/
	public static final int CACHE_TYPE_FIFO = 1;
	/** 最近最少使用*/
	public static final int CACHE_TYPE_LRU = 2;
	/** map*/
	public static final int CACHE_TYPE_MAP = 3;

	private static final long serialVersionUID = 8332661566419637060L;

	protected MCache(String id) {
		super(id);
		this.cacheType = CACHE_TYPE_LRU;
	}

	@Column(length=255, comment="缓存名称")
	private String name;
	
	@Column(comment="最大占用内存[字节]")
	private long maxCacheSize;
	
	@Column(comment="cache中项的最大保存时间[毫秒]")
	private long maxLifetime;
	
	@Column(comment="是否开启")
	private boolean opened;
	
	@Column(comment="缓存类型[1:先进先出; 2:最近最少使用; 3:map]")
	private int cacheType;
	
	@UnSave
	private Cache<String, ?> cache;
	@UnSave private Class<?> clazz;
	
	public String getName() {
		return name;
	}

	public void setName(String name) {
		this.name = name;
	}

	public long getMaxCacheSize() {
		return maxCacheSize;
	}

	public void setMaxCacheSize(long maxCacheSize) {
		this.maxCacheSize = maxCacheSize;
	}

	public long getMaxLifetime() {
		return maxLifetime;
	}

	public void setMaxLifetime(long maxLifetime) {
		this.maxLifetime = maxLifetime;
	}

	public boolean isOpened() {
		return opened;
	}

	public void setOpened(boolean opened) {
		this.opened = opened;
	}

	public Cache<String, ?> getCache() {
		return cache;
	}

	public void setCache(Cache<String, ?> cache) {
		this.cache = cache;
	}

	public int getSize() {
		if (cache == null) {
    		return 0;
    	}
		return cache.size();
	}
	
	public int getCacheSize() {
		if (cache == null) {
    		return 0;
    	}
    	return this.cache.getCacheSize();
    }

    public long getCacheHits() {
    	if (cache == null) {
    		return 0;
    	}
    	return cache.getCacheHits();
    }

    public long getCacheMisses() {
    	if (cache == null) {
    		return 0;
    	}
    	return cache.getCacheMisses();
    }
    
	public int getCacheType() {
		return cacheType;
	}

	public void setCacheType(int cacheType) {
		this.cacheType = cacheType;
	}

	@JSONField(serialize = false)
	public Class<?> getClazz() {
		if (clazz != null) {
			return clazz;
		}
		
		try {
			return Class.forName(name);
		} catch (ClassNotFoundException e) {
			return null;
		}
	}

}
